package es.onlysolutions.gs.web.controller;

import es.onlysolutions.arq.core.mvc.command.AbstractCommandBean;
import es.onlysolutions.gs.comm.entity.VideoProcess;
import es.onlysolutions.gs.comm.facade.VideoFacade;
import es.onlysolutions.gs.web.commandBean.CheckVideoStateBean;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * controller that checks the state of the video.
 */
public class CheckVideoStateController extends GSController
{

    private VideoFacade videoFacade;

    public void setVideoFacade(VideoFacade videoFacade)
    {
        this.videoFacade = videoFacade;
    }

    /**
     * Request param to set the video id.
     */
    public static String REQUEST_PARAM_VIDEO = "vp";

    
    protected AbstractCommandBean loadPage(HttpServletRequest request) throws Exception
    {
        CheckVideoStateBean bean = new CheckVideoStateBean();

        Long idVideo = ServletRequestUtils.getLongParameter(request, REQUEST_PARAM_VIDEO, -1);

        if( idVideo != null && idVideo > 0 )
        {
            VideoProcess videoProcess = (VideoProcess) videoFacade.get(VideoProcess.class, idVideo);
            if( videoProcess != null )
            {
                bean.setVideoProcess( videoProcess );
            }
        }

        return bean;
    }


    @Override
    protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException bindException) throws Exception
    {
        CheckVideoStateBean bean = (CheckVideoStateBean) command;
        VideoProcess video = bean.getVideoProcess();//Incomplete entity to improve the performance.

        String youTubeId = video.getYouTubeId();
        Integer stateCode = videoFacade.getStatusOfVideo( youTubeId, bean.getYouTubeUsername(), bean.getYouTubePassword() );

        bean.setVideoProcess((VideoProcess) videoFacade.load(VideoProcess.class, video.getId()));
        bean.setStateCode( stateCode );

        return new ModelAndView( getSuccessView(), getCommandName(), bean );
    }
}
